<template>
  <div class="current-students">
    <div class="current-students-search">
      <div class="use-btn">
        <div class="collapse-btn" @click="setCollapse">
          <span v-if="isCollapse"
            >展开<el-icon style="margin-left: 10px"
              ><ArrowDown /></el-icon></span
          ><span v-else
            >收起<el-icon style="margin-left: 10px"><ArrowUp /></el-icon
          ></span>
        </div>
      </div>
      <el-form :model="form" ref="ruleFormRef" label-width="auto">
        <el-row :gutter="0" style="margin-bottom: 10px">
          <el-col :span="6">
            <el-form-item label="搜索学员:">
              <el-input
                v-model="searchName"
                style="width: 80%"
                placeholder="请输入学员姓名/手机号"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报读课程:">
              <el-select
                v-model="lessonName"
                placeholder="请选择课程"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in lessonList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所在班级:">
              <el-select
                v-model="classN"
                placeholder="请选择班级"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in registrarStore.classList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" icon="Search" @click="toSearch"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="toClear(ruleFormRef)"
              >重置</el-button
            >
          </el-col>
        </el-row>
        <div class="search-collapse" v-show="isCollapse">
          <el-row :gutter="0" style="margin-bottom: 10px">
            <el-col :span="6" style="padding-right: 4%">
              <el-form-item label="到期日期:">
                <el-date-picker
                  v-model="cTime"
                  type="daterange"
                  unlink-panels
                  range-separator="~"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 80%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="班级老师:">
                <el-select
                  v-model="classPeople"
                  placeholder="请选择班级老师"
                  style="width: 80%"
                  clearable
                >
                  <el-option
                    v-for="item in teacherList"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="剩余数量:">
                <el-input
                  v-model="remainderLessonNum"
                  style="width: 80%"
                  placeholder="请输入剩余数量"
                  type="number"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="收费方式:">
                <el-select
                  v-model="value"
                  placeholder="请选择学员来源"
                  style="width: 80%"
                >
                  <el-option
                    v-for="item in studentsSource"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="剩余数量:">
                <el-select
                  v-model="value"
                  placeholder="请选择学员来源"
                  style="width: 80%"
                >
                  <el-option
                    v-for="item in studentsSource"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
          <!-- <el-row :gutter="0" style="margin-bottom: 10px">
            <el-col :span="6">
              <el-form-item label="课程类型:"> </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="班级老师:"> </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="结课状态:"> </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="0" style="margin-bottom: 10px">
            <el-col :span="6">
              <el-form-item label="是否停课:"> </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否超上:"> </el-form-item>
            </el-col>
          </el-row> -->
        </div>
      </el-form>
    </div>
    <div class="manage-students">
      <!-- <el-button type="primary">发消息</el-button> -->
      <el-button
        plain
        @click="openShareDialog('跟进人')"
        v-hasPermi="['sales:clue:distribute']"
        >分配跟进人</el-button
      >
      <el-button
        plain
        @click="openShareDialog('学管师')"
        v-hasPermi="['student:manager:add']"
        >分配学管师</el-button
      >
      <!-- <el-button type="plain" plain icon="Upload" @click="handleImport"
        >导入报读信息</el-button
      > -->
      <el-button type="plain" plain icon="Download" @click="handleExport"
        >导出</el-button
      >
    </div>
    <div class="dialog-warning">
      <span>剩余课时数(课时) : </span
      ><span style="font-weight: bolder; margin: 0 20px 0 10px">{{
        remainderLessonTotal
      }}</span>
      <span>剩余课消金额(元) : </span
      ><span style="font-weight: bolder; margin: 0 20px 0 10px">{{
        remainderAmountTotal
      }}</span>
      <el-tooltip
        class="box-item"
        effect="dark"
        content="包括未消耗的课时"
        placement="top"
      >
        <el-icon size="16px"><QuestionFilled /></el-icon>
      </el-tooltip>
    </div>
    <!-- 表格 -->
    <div class="students-table">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="学员姓名" fixed="left" width="180">
          <template #default="scope">
            <router-link
              :to="'/registrar/studentsDetails/detail/' + scope.row.id"
              class="link-type"
            >
              <div style="display: flex; align-items: center">
                <span
                  style="margin-right: 10px; color: #67c23a; cursor: pointer"
                  >{{ scope.row.name }}</span
                >
                <el-icon v-if="scope.row.gender == '1'" style="color: #fb6465"
                  ><Female
                /></el-icon>
                <el-icon
                  v-else-if="scope.row.gender == '0'"
                  style="color: #4791ed"
                  ><Male
                /></el-icon>
              </div>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column
          property="mobile"
          label="手机号"
          fixed="left"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="courseName"
          label="报读课程"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="className"
          label="所在班级"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          label="购买数量(含赠送)"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        >
          <template #default="scope">
            {{ scope.row.countLessonTotal }}课时
          </template>
        </el-table-column>

        <el-table-column
          label="赠送数量"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        >
          <template #default="scope">
            {{ scope.row.freeClassHours }}课时
          </template>
        </el-table-column>

        <el-table-column
          label="已消耗数量"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        >
          <template #default="scope">
            {{ scope.row.countLessonComplete }}课时
          </template>
        </el-table-column>

        <el-table-column
          label="退转数量"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        >
          <template #default="scope">
            {{ scope.row.countLessonRefund }}课时
          </template>
        </el-table-column>
        <el-table-column
          label="剩余数量"
          :header-cell-style="headerCellStyle"
          :formatter="formatName"
          width="130"
        >
          <template #header>
            <span style="margin-right: 8px">剩余数量</span>
            <el-tooltip
              class="item"
              effect="dark"
              content="剩余数量=购买数量-已消耗数量-退转数量"
              placement="top"
            >
              <el-icon color="#C0C4CC" size="16px"><QuestionFilled /></el-icon>
            </el-tooltip>
          </template>
          <template #default="scope">
            {{ scope.row.remainderLesson }}课时
          </template>
        </el-table-column>

        <el-table-column
          label="课消金额"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        >
          <template #default="scope">
            ¥
            {{
              scope.row.spendAmount > 0 ? scope.row.spendAmount.toFixed(2) : 0
            }}
          </template>
        </el-table-column>

        <el-table-column
          label="剩余课消金额"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        >
          <template #default="scope">
            ¥
            {{
              scope.row.remainderAmount > 0
                ? scope.row.remainderAmount.toFixed(2)
                : 0
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="到期日期"
          :header-cell-style="headerCellStyle"
          :formatter="formatName"
          width="130"
        >
          <template #header>
            <span style="margin-right: 8px">到期日期</span>
            <el-tooltip
              class="item"
              effect="dark"
              content="该时间是创建订单时所设置的课程有效期时间"
              placement="top"
            >
              <el-icon color="#C0C4CC" size="16px"><QuestionFilled /></el-icon>
            </el-tooltip>
          </template>
          <template #default="scope">
            {{ scope.row.expireDate ? scope.row.expireDate : "长期有效" }}
          </template>
        </el-table-column>
        <el-table-column
          property="absencesNum"
          label="缺课次数"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="counselor"
          label="跟进人"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="management"
          label="学管师"
          show-overflow-tooltip
          :formatter="formatName"
          fixed="right"
          width="130"
        />
        <!-- <el-table-column label="操作" width="130" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <pagination
        :total="total"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        @pagination="toGetEnrollmentStudentsList"
      />
      <div style="height: 10px"></div>
    </div>
    <ShareDialog
      :isShowShare="isShowShare"
      :shareType="shareType"
      :students="multipleSelection"
      @update:isShowShare="updateShowShare"
      @update:tableList="toGetEnrollmentStudentsList"
    />
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?stage=4'"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="cancelImport">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Pagination from "@/components/Pagination/index.vue";
import ShareDialog from "../shareDialog/index.vue";
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import useRegistrarStore from "@/store/modules/registrar";

import {
  getEnrollmentStudentsList,
  getLessonList,
  remainderCount,
  getTeacherList,
  toEenrollExport,
  toExportTemplate,
} from "@/api/studentManagement/index.js";
import {
  getToken,
  getLoginDeptParentAuth,
  getLoginDeptAuth,
} from "@/utils/auth";
const { proxy } = getCurrentInstance();
//获取仓库数据
const registrarStore = useRegistrarStore();
//筛选
const searchName = ref(""); //学员搜索
const remainderLessonNum = ref("");
const cTime = ref("");
//获取学员来源下拉列表
const searchJoinWay = ref(""); //学员来源
// const joinWayList = reactive([]) //学员来源列表

//获取工作人员下拉列表
// const people = ref('') //跟进人
// const studyPeople = ref('') //学管师
// const peopleList = reactive([]) //工作人员列表

//获取所在班级下拉列表
const classN = ref("");
//班级老师
const teacherList = ref([]);
const classPeople = ref(""); //班级老师
const toGetTeacherList = async () => {
  try {
    const res = await getTeacherList({});
    if (res.code == 200) {
      teacherList.value = res.data;
    }
  } catch (error) {
    console.error("获取班级老师下拉列表失败:", error);
  }
};
onMounted(toGetTeacherList);

//获取年级下拉列表
// const gradeName = ref('')
// const gradeList = reactive([]) //所在班级列表

//获取课程列表
const lessonName = ref("");
const lessonList = ref([]);
const toGetLessonList = async () => {
  try {
    const res = await getLessonList({
      state: 0,
      pageNum: 1,
      pageSize: 9999,
      open: 1,
    });
    if (res.code == 200) {
      lessonList.value = res.rows;
    }
  } catch (error) {
    console.error("获取学生的信息失败:", error);
  }
};
onBeforeMount(toGetLessonList);

//筛选学员列表
function toSearch() {
  toGetEnrollmentStudentsList();
}

//控制折叠
const isCollapse = ref(true);
function setCollapse() {
  isCollapse.value = !isCollapse.value;
}
//控制分配弹窗
const isShowShare = ref(false);
const shareType = ref(1);

const openShareDialog = (type) => {
  if (multipleSelection.value.length) {
    isShowShare.value = true;
    shareType.value = type;
  } else {
    ElMessage({
      message: "请选择要分配的学员",
      type: "warning",
    });
  }
};
const updateShowShare = (value) => {
  isShowShare.value = value;
};

//表格多选操作
const multipleTableRef = ref();
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log("444", multipleSelection.value);
};
//表格没有数据显示'-'
const formatName = (row, column, cellValue) => {
  return cellValue === "" || cellValue === null ? "-" : cellValue;
};
//分页器
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
//处理日期格式
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以加1
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};
//获取表格数据
const tableData = ref([]);
const toGetEnrollmentStudentsList = async () => {
  const params = {
    stage: 4,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    wxParam: searchName.value,
    remainderLesson: remainderLessonNum.value,
    courseId: lessonName.value,
    classId: classN.value,
    teacherId: classPeople.value,
    startTime: cTime.value ? formatDate(cTime.value[0]) : "",
    endTime: cTime.value ? formatDate(cTime.value[1]) : "",
  };
  try {
    const res = await getEnrollmentStudentsList(params);
    if (res.code == 200) {
      total.value = res.total;
      tableData.value = res.rows;
      console.log("55555", tableData.value);
    }
  } catch (error) {
    console.error("获取学生列表失败:", error);
  }
};
onMounted(toGetEnrollmentStudentsList);
//删除学员
const handleDelete = (row) => {
  ElMessageBox.confirm("是否删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteClue({
          id: row.id,
          type: 1,
        });
        if (res.code == 200) {
          toGetCurrentStudentsList();
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "删除失败",
          });
        }
      } catch (error) {
        console.error("删除失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
//清空搜索内容
const toClear = () => {
  searchName.value = "";
  classN.value = "";
  lessonName.value = "";
  classPeople.value = "";
  cTime.value = "";
  remainderLessonNum.value = "";

  toGetEnrollmentStudentsList();
};
// 获取剩余课消金额、课时总数
const remainderLessonTotal = ref("");
const remainderAmountTotal = ref("");
const toGetRemainderCount = async () => {
  try {
    const res = await remainderCount({});
    if (res.code == 200) {
      remainderLessonTotal.value = res.data.remainderLessonTotal;
      remainderAmountTotal.value = res.data.remainderAmountTotal;
    }
  } catch (error) {
    console.error("获取剩余课消金额、课时总数失败:", error);
  }
};
onBeforeMount(toGetRemainderCount);

//导入导出部分---------------------------------------------------------
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "导入学员",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  // updateSupport: 0,
  // 设置上传的请求头部
  headers: {
    Authorization: "Bearer " + getToken(),
    LoginDeptParentAuth: getLoginDeptParentAuth(),
    LoginDeptAuth: getLoginDeptAuth(),
  },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "student/importEnroll",
});
//导入
function handleImport() {
  upload.open = true;
  //importClassListAPI().then((res) => {});
}
//确定导入
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
//取消导入
const cancelImport = () => {
  upload.open = false;
  proxy.$refs["uploadRef"].clearFiles();
};
const handleFileSuccess = (res) => {
  upload.open = false;
  proxy.$refs["uploadRef"].clearFiles();
  pageNum.value = 1;
  toGetEnrollmentStudentsList();
  if (res.code == 200) {
    ElMessage({
      message: res.msg,
      type: "success",
    });
  } else {
    ElMessage({
      message: res.msg,
      type: "error",
    });
  }
};
const handleFileError = (err) => {
  console.log("上传失败:", err);
  ElMessage({
    message: "上传失败",
    type: "error",
  });
};

//导出
function handleExport() {
  toEenrollExport({ stage: 4 }).then((res) => {
    let blob = new Blob([res], {
      type: "application/vnd.ms-excel;charset=utf-8",
    });
    //var contentDisposition = decodeURI(res.headers["content-disposition"]);
    const url = window.URL.createObjectURL(blob),
      link = document.createElement("a"); // 创建a标签
    link.href = url;
    link.download = "报读情况列表";
    link.click();
    URL.revokeObjectURL(url); // 释放内存
    proxy.$modal.msgSuccess("导出成功");
  });
}

/** 下载模板操作 */
function importTemplate() {
  toExportTemplate({ stage: 4 })
    .then((res) => {
      let blob = new Blob([res], {
        type: "application/vnd.ms-excel;charset=utf-8",
      });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "导入模板.xls";
      document.body.appendChild(a); // 添加到 DOM
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    })
    .catch((error) => {
      console.error("下载模板失败:", error);
    });
}
</script>

<style lang="scss" scoped>
.current-students {
  .current-students-search {
    position: relative;
    .use-btn {
      position: absolute;
      top: 0;
      right: 0;
      height: 30px;
      z-index: 100;

      cursor: pointer;
      .collapse-btn {
      }
    }
    .search-label {
      display: inline-block;
      width: 18%;
      text-align: right;
      margin-right: 8px;
      font-size: 14px;
    }
    .current-students-search-main {
      width: 90%;

      .search-collapse {
        // height: 500px;
        // background-color: red;
      }
    }
  }
  .manage-students {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    height: 40px;
    // background-color: red;
  }
  .dialog-warning {
    // margin-bottom: 15px;
    padding: 8px 10px;
    background-color: #ecf5ff;
    display: flex;
    align-items: center;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.65);
  }
}
</style>
